#include <stdio.h>
#include <stdlib.h>
#include <string.h> // system

#include "opt.h"
#include "acnstdtypes.h"
#include "acn_port.h"
#include "common_func.h"
#include "acnlog.h"  //acn global
#include "component.h"

#include "init_appl.h"
#include "discover.h"
#include "slp.h"
#include "property.h"



/************function declare******************/
void do_client();

/*****************global configure variable ******************/
extern component_t *local_component; //declared in init_appl.c
extern bool regiest_ok ;//declared in discover.c
extern char *dcid_str1;
bool is_client = true;

int main()
{
	//server only can run one object
  if(is_running()) {return 0;}
  acn_port_protect_startup();
  /********read config*****************/
  readConifgs();
  /****** initial part *****************/
  init_protcols_stack();
  init_component();
  /****** while part ******************/
  if(is_client){
	  do_client();
  }else{
  }
  /******release part ******************/
  discover_deregister(local_component);
  release_protcols_stack();
  acn_port_protect_shutdown();
  close_running();
  return 0;
}


void do_client()
{
	int max_slp_time = MAX_FINDDATIME;
	bool do_exit = false;
	printf("Now try to find SLP DA server to register myself \n");
	while(1){
		printf("..");
		if(slp_get_da_count()) {
			printf("\n");
			break;
		}
		sleep(1);
		if(!(max_slp_time--)) {
			printf("\n");
			printf("can't found DA after %d seconds and the application can't start up \n",MAX_FINDDATIME);
			printf("now retry \n");
			max_slp_time = 	MAX_FINDDATIME;
			continue;
		}
	}
	printf("founding DA successful now register myself to DA \n" );
	discover_register(local_component);
	max_slp_time = MAX_FINDDATIME;
	while(1){
		printf("..");
		discover_acn(dcid_str1,NULL);
		sleep(1);
		if(regiest_ok){
			printf("\n");
			printf("register my self OK ,now starting service \n");
			break;
		}
		if(!(max_slp_time--)) {
			printf("can't register myself after %d seconds and the application can't start up \n",MAX_FINDDATIME);
			break;
		}
	}
	while(1){
		switch(mygetch()){
		case 'x':case 'X':
			do_exit = true;
			return;
		}
	}

}


